<?php
/**
 * Created by PhpStorm.
 * User: hd-1
 * Date: 2018/8/24
 * Time: 19:41
 */
namespace app\admin\controller;

use app\common\lib\Tool;
use think\Db;
use think\Request;

class User extends Base
{
    public function index(){
        $Arr = input();
        if(!empty($Arr['username'])){
            $map[] =  ['username', 'like', "%".$Arr['username']."%"];
            $map[] =  ['username','neq','admin'];
        }else{
            $map[] = ['username','neq','admin'];
        }
        $Ret = Db::table('admin_user')->where($map)->paginate(5,false,['query' => request()->param()]);

        $page = $Ret->render();

        return $this->fetch('user/member-list',['data'=>$Ret,'map'=>$Arr,'page'=>$page]);
    }

    public function add(Request $request){
        if($request->isPost()){
            $Arr = input();
            $data = [
                'username'=>$Arr['username'],
                'password'=>pwd_encrypt($Arr['pass']),
                'add_time'=>time(),
                'status'=>1,
            ];
            $Ret = Db::table('admin_user')->insert($data);
            if($Ret){
                return Tool::json(1,[],'添加用户成功');
            }else{
                return Tool::json(0,[],'添加用户失败');
            }
        }else{
            return view('user/member-add');
        }
    }

    public function update( Request $request){
        $Arr = input();
        if($request->isPost()){
            $data = [
                'username'=>$Arr['username'],
                'password'=>pwd_encrypt($Arr['pass']),
            ];
            $map['id'] = $Arr['id'];
            $Ret = Db::table('admin_user')->where($map)->update($data);
            if($Ret){
                return Tool::json(1,[],'修改用户成功');
            }else{
                return Tool::json(0,[],'修改用户失败');
            }
        }else{
            $adminUserArr = Db::table('admin_user')->where(['id'=>$Arr['id']])->find();

            return view('user/member-edit',['adminUserArr'=>$adminUserArr]);
        }
    }

    public function deleteUser(){
        $id = input('id');
        $Ret = Db::table('admin_user')->where('id',$id)->delete();
        if($Ret){
            return Tool::json(1,[],'删除用户成功');
        }else{
            return Tool::json(0,[],'删除用户失败');
        }
    }
}